/*
	the first iteration of the Java to C communications still used by Test_Main
	by Ryan Higgins 
	
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/poll.h>
#include <unistd.h>
#include "serialio.h"

int main(int argc, char* argv[])
{
	int pid;
	struct pollfd ufds;
	int res = 0;
	ssize_t wrote, sRed, sWrote, red;
	int fromSerial = -1;
	int toSerial = -1;
	char* sMessage[1024];
	char* message[1024];	
	if (argc != 3){   /* check for valid number of command-line arguments */ 
		fprintf(stderr, "Usage: %s + to pipe + from pipe\n", argv[0]);
		return 1; 
	}
	open_serial(0);
	setup_serial_params();
	pid = fork();
	if(pid == 0){
		fromSerial = open(argv[1], O_WRONLY | O_APPEND, S_IWUSR);
		fprintf(stderr, "C - fromSerial's file descripter is - %d\n", fromSerial);
		for(;;){
			//read it from the serial port
			sRed = read(serial_params.fd, sMessage, 1024);
			//print a status message	
			fprintf(stdout, "C - received from serial and writing to java - %d bytes\n", sRed, sMessage);
			//write it to JavaPipe (fromSerial)
			if(sRed > 0){wrote = write(fromSerial,sMessage , sRed);}
		}
	}else{
		toSerial = open(argv[2], O_RDONLY, S_IRUSR);
		fprintf(stderr, "C - toSerial's file descripter is - %d\n", toSerial);
		for(;;){
			//read message from Javapipe 
	       		red = read(toSerial, message, 1024);
			if(red > 0){
				//print a status message
				fprintf(stdout, "C received from Java and writing to Serial - %d bytes\n",red, message);
				//write it to the serial port
				sWrote = write(serial_params.fd, message, red);
				
			}
		}
	}
	return 0;
}
